﻿//-----------------------------------------------------------------------
// <copyright>
// Copyright (C) Sergey Solyanik for The Black Square Project.
//
// This file is subject to the terms and conditions of the Microsoft Public License (MS-PL).
// See http://www.microsoft.com/opensource/licenses.mspx#Ms-PL for more details.
// </copyright>
//----------------------------------------------------------------------- 
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Services;

using DataModel;
using DocumentManager;

/// <summary>
/// Summary description for BlackSquare
/// </summary>
[WebService(Namespace = "http://www.solyanik.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class BlackSquare : System.Web.Services.WebService
{
    private Regex FileNameParser = new Regex(@"^.*\.(\d+)(\[\d+\])?\.docx$",
        RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);

    /// <summary>
    /// Trivial constructor.
    /// </summary>
    public BlackSquare()
    {
    }

    /// <summary>
    /// Enters a newly reviewed document (just one) into the system.
    /// </summary>
    /// <param name="fileName"> The name of the file. Must be in the form "filename.fileid[randomnumber].docx. </param>
    /// <param name="fileBytes"> The file contents. </param>
    /// <param name="comment"> Review comment. </param>
    /// <param name="verdict"> Review verdict. One of: 0 ("Needs work"), 1 ("LGTM with minor tweaks"), 2 ("LGTM"), 
    ///     3 ("Non-scoring comment"). </param>
    [WebMethod]
    public void UploadReviewedDocument(string fileName, byte[] fileBytes, string comment, int verdict)
    {
        if (!HttpContext.Current.User.Identity.IsAuthenticated)
            return;

        using (BlackSquareDataContext dataContext = new BlackSquareDataContext(
            System.Configuration.ConfigurationManager.ConnectionStrings["DataConnectionString"].ConnectionString))
        {
            Match m = FileNameParser.Match(fileName);
            if (!m.Success)
                throw new ArgumentException(fileName);

            int versionId = int.Parse(m.Groups[1].Value);

            DocumentVersion[] versions =
                (from vv in dataContext.DocumentVersions where vv.Id == versionId select vv).ToArray();
            if (versions.Length != 1)
                throw new ArgumentException(fileName);

            DocumentVersion version = versions[0];
            int documentSetId =
                (from ds in dataContext.Documents where ds.Id == version.DocumentId select ds.Id).Single();

            string targetFile = Path.GetTempFileName();
            string newFile = Path.GetTempFileName();
            try
            {
                File.WriteAllBytes(targetFile, version.Contents.ToArray());
                File.WriteAllBytes(newFile, fileBytes);

                DocumentUtils.MergeComments(targetFile, newFile);
                DocumentUtils.RemoveDuplicateComments(targetFile);
                byte[] bytes = File.ReadAllBytes(targetFile);
                dataContext.UpdateVersion(bytes, versionId);

                dataContext.AddReview(documentSetId, (byte)verdict, comment);
            }
            finally
            {
                File.Delete(targetFile);
                File.Delete(newFile);
            }
        }
    }
}

